

package cn.edu.nsmc.modules.sys.controller;

import cn.edu.nsmc.common.annotation.SysLog;
import cn.edu.nsmc.common.utils.Constant;
import cn.edu.nsmc.common.utils.PageUtils;
import cn.edu.nsmc.common.utils.R;
import cn.edu.nsmc.common.validator.Assert;
import cn.edu.nsmc.common.validator.ValidatorUtils;
import cn.edu.nsmc.common.validator.group.AddGroup;
import cn.edu.nsmc.common.validator.group.UpdateGroup;
import cn.edu.nsmc.modules.sys.dao.SysUserDao;
import cn.edu.nsmc.modules.sys.dao.SysUserRoleDao;
import cn.edu.nsmc.modules.sys.entity.SysUserEntity;
import cn.edu.nsmc.modules.sys.entity.SysUserRoleEntity;
import cn.edu.nsmc.modules.sys.entity.vo.SysUserVO;
import cn.edu.nsmc.modules.sys.form.PasswordForm;
import cn.edu.nsmc.modules.sys.service.SysUserRoleService;
import cn.edu.nsmc.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 *
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysUserDao sysUserDao;


	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
		if(getUserId() != Constant.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}
		PageUtils page = sysUserService.queryPage(params);

		return R.ok().put("page", page);
	}

	@RequestMapping("/list/vo")
	public R listSysUserVo(@RequestParam Map<String, Object> params){
		PageUtils page = sysUserService.queryPageSysUserVO(params);

		return R.ok().put("page", page);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}


	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody PasswordForm form){
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");

		//sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		//sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	@PostMapping("/wxChangePassword")
	public R wxChangePassword(@RequestBody PasswordForm form){
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");

		SysUserEntity user = sysUserService.queryByMobile(form.getMobile());
		if (user == null){
			return R.error("用户不存在");
		}
		// sha256加密
		String oldPassword = new Sha256Hash(form.getPassword(), user.getSalt()).toHex();
		// //sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), user.getSalt()).toHex();

		//更新密码
		boolean flag = sysUserService.updatePassword(user.getUserId(), oldPassword, newPassword);
		if (!flag){
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	// @RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.getById(userId);

		SysUserVO userVO = new SysUserVO();
		userVO.setRoleId(sysUserRoleDao.getRoleIdByUserId(userId));
		BeanUtils.copyProperties(user, userVO);
		//获取用户所属的角色列表
		// List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		// user.setRoleIdList(roleIdList);

		return R.ok().put("user", userVO);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user,Long roleId){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		user.setCreateUserId(getUserId());
		if (roleId!=null){
			//todo : 一个管理员可拥有多个角色
			ArrayList<Long> objects = new ArrayList<>();
			objects.add(roleId);
			user.setRoleIdList(objects);
		}
		sysUserService.saveUser(user);
		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.update(user);

		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@PostMapping("/wx/update")
	public R wxUpdate(@RequestBody SysUserEntity user){


		return R.ok().put("data",sysUserService.wxUpdate(user));
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}

		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}

		sysUserService.deleteBatch(userIds);

		return R.ok();
	}

	//批量导入导出
	@GetMapping("getExcelTemplate")
	public void getExcelTemplate(HttpServletResponse response) throws IOException {
		sysUserService.getExcelTemplate(response);
	}

	@PostMapping("importUser")
	public R importUser(@RequestBody MultipartFile file) {
		//System.out.println(getUserId());
		return sysUserService.importUser(file, getUserId());
	}

	@PostMapping("exportUser")
	public void exportUser(@RequestBody SysUserEntity sysUserEntity, HttpServletResponse response) throws IOException {
		sysUserService.exportUser(sysUserEntity, response);
	}

	@GetMapping("nameList")
	public R nameList(String name) {
		return sysUserService.nameList(name);
	}

	@GetMapping("getOneById")
	public R getOneById(Long id) {
		return sysUserService.getOneById(id);
	}
}
